package com.ruoyi.kenuo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.RandomUtil;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.kenuo.domain.EmailLog;
import com.ruoyi.kenuo.enums.SmsMy;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.kenuo.domain.PoloSmsLog;
import com.ruoyi.kenuo.service.IPoloSmsLogService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 短信验证码Controller
 *
 * @author polo
 * @date 2022-10-19
 */
@RestController
@RequestMapping("/kenuo/sms")
@Api(tags = "发送短信验证码")
public class PoloSmsLogController extends BaseController
{

    @Autowired
    private IPoloSmsLogService poloSmsLogService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RedisCache redisCache;


    @GetMapping("/getDict/list")
    public TableDataInfo list(SysDictData dictData)
    {
        startPage();
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }
    /**
     * 发送验证码接口
     * @param poloSmsLog
     * @return
     */
    @PostMapping("/send")
    @ApiOperation(value = "发送验证码",notes = "用户发送验证码会把上次的验证码过期掉")
    public AjaxResult send(@RequestBody PoloSmsLog poloSmsLog) {
        String mobile = poloSmsLog.getUserPhone();
        if(StringUtils.isEmpty(mobile)){
            throw new RuntimeException("未获取到手机号码！");
        }

        AjaxResult ar = poloSmsLogService.sendHUYiSms(SmsMy.VALID,Long.valueOf("1"),mobile,new HashMap());
        return ar;
    }
    /**
     * 发送邮箱验证码接口
     * @param EmailLog
     * @return
     */
    @PostMapping("/sendMail")
    @ApiOperation(value = "发送邮箱验证码",notes = "发送邮箱验证码")
    public AjaxResult sendMail(@RequestBody EmailLog em) {
        String receive = em.getReceiver();
        if(StringUtils.isEmpty(receive)){
            throw new RuntimeException("未获取到需要发送的邮箱！");
        }
        AjaxResult ar = poloSmsLogService.sendEmail(em);
        return ar;
    }
    /**
     * 重置密码
     * @param EmailLog
     * @return
     */
    @PostMapping("/resetPassword")
    public AjaxResult resetPassword(@RequestBody EmailLog em) {
        //邮件接收人
        String receiver = em.getReceiver();
        if(StringUtils.isEmpty(receiver)){
           return AjaxResult.error("未获取到需要发送的邮箱！");
        }
        String code = em.getVerifyCode();
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("未获取到邮箱验证码！");
        }
        //密码
        String password = em.getPassword();
        if(StringUtils.isEmpty(password)){
            return AjaxResult.error("密码为空！");
        }
        AjaxResult ar = poloSmsLogService.resetPassword(em);
        return ar;
    }
    /**
     * 密保--重置密码
     * @param EmailLog
     * @return
     */
    @PostMapping("/resetQuePass")
    public AjaxResult resetQuePass(@RequestBody EmailLog em) {
        //账号
        String username = em.getUsername();
        if(StringUtils.isEmpty(username)){
            return AjaxResult.error("账号不能为空！");
        }
        //密保
        String question = em.getQuestion();
        //密保问题验证
        SysUser user = userService.selectUserByUserName(username);
        String ques = user.getQuestion();
        if(null!=ques&&!question.equals(ques)){
            return AjaxResult.error("密保问题不正确！");
        }
        //密码
        String password = em.getPassword();
        if(StringUtils.isEmpty(password)){
            return AjaxResult.error("密码为空！");
        }
        AjaxResult ar = poloSmsLogService.resetQuePass(em);
        return ar;
    }
    /**
     * 核对验证码接口
     * @param poloSmsLog
     * @return
     */
    @PostMapping("/checkMyCode")
    @ApiOperation(value = "核对验证码",notes = "核对验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "userPhone", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "mobileCode", value = "手机验证码", required = true, dataType = "String")
    })
    public AjaxResult checkMyCode(@RequestBody PoloSmsLog poloSmsLog) {
        String mobile = poloSmsLog.getUserPhone();
        if(StringUtils.isEmpty(mobile)){
            throw new RuntimeException("未获取到手机号码！");
        }
        if(StringUtils.isEmpty(poloSmsLog.getMobileCode())){
            throw new RuntimeException("未获取到手机验证码！");
        }

        AjaxResult ar = poloSmsLogService.checkMyCode(poloSmsLog);
        return ar;
    }
    /**
     * 查询短信验证码列表
     */
    @PreAuthorize("@ss.hasPermi('kenuo:log:list')")
    @GetMapping("/list")
    public TableDataInfo list(PoloSmsLog poloSmsLog)
    {
        startPage();
        List<PoloSmsLog> list = poloSmsLogService.selectPoloSmsLogList(poloSmsLog);
        return getDataTable(list);
    }

    /**
     * 导出短信验证码列表
     */
    @PreAuthorize("@ss.hasPermi('kenuo:log:export')")
    @Log(title = "短信验证码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PoloSmsLog poloSmsLog)
    {
        List<PoloSmsLog> list = poloSmsLogService.selectPoloSmsLogList(poloSmsLog);
        ExcelUtil<PoloSmsLog> util = new ExcelUtil<PoloSmsLog>(PoloSmsLog.class);
        util.exportExcel(response, list, "短信验证码数据");
    }

    /**
     * 获取短信验证码详细信息
     */
    @PreAuthorize("@ss.hasPermi('kenuo:log:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(poloSmsLogService.selectPoloSmsLogById(id));
    }

    /**
     * 新增短信验证码
     */
    @PreAuthorize("@ss.hasPermi('kenuo:log:add')")
    @Log(title = "短信验证码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PoloSmsLog poloSmsLog)
    {
        return toAjax(poloSmsLogService.insertPoloSmsLog(poloSmsLog));
    }

    /**
     * 修改短信验证码
     */
    @PreAuthorize("@ss.hasPermi('kenuo:log:edit')")
    @Log(title = "短信验证码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PoloSmsLog poloSmsLog)
    {
        return toAjax(poloSmsLogService.updatePoloSmsLog(poloSmsLog));
    }

    /**
     * 删除短信验证码
     */
    @PreAuthorize("@ss.hasPermi('kenuo:log:remove')")
    @Log(title = "短信验证码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(poloSmsLogService.deletePoloSmsLogByIds(ids));
    }
}
